import { getUserInfo, getUserPhone, updateUserInfo, } from "../../api/user"
import { appRequestUrl, defaultConfig, shareAppMessageSet } from "../../utils/config"
import { dataCollection } from "../../utils/dataCollection"
import { loginInstance } from "../../utils/login"
import { phoneHide } from "../../utils/util"
import { LogoAnimate } from "./animate"

let app = getApp()
let logoAnimate: LogoAnimate = new LogoAnimate()
Page({
  data: {
    phone: '',
    code: '',
    isAgreementProtocol: false,//是否勾选了协议
    classVisible: false,
    hidden: false,
    avatar: '',
    nickname: '',
    logo: '',//小程序logo
    accessToken: '',
    openId: '',
    sessionKey: '',
    newUser: true,
    dataLoad: false,
    visible: false,
    showPhone: '',
    themeCode: '',
    drivingSchoolLogo: '',
    miniLogoNotText: '',
    miniLogo: '',
    defaultHeadPortrait: '',
    checkIcon: '',
  },
  onLoad: function () {
    const themeCode = wx.getStorageSync('themeCode')
    this.setData({
      themeCode,
      drivingSchoolLogo: wx.getStorageSync('currentDrivingSchool').logo ?? defaultConfig.logo,
      drivingSchoolShortName: wx.getStorageSync('currentDrivingSchool').shortName ?? defaultConfig.shortName,
      miniLogoNotText: app.globalData.dictMap.get('miniLogoNotText'),
      miniLogo: app.globalData.dictMap.get('miniLogo')
    })
    //清楚定时器
    loginInstance.JudgmentExpirationInstance.clear()
    //页面开始加载
    // wx.showLoading({
    //   title: '加载中...',
    //   mask: true
    // })
    //开始获取token
    loginInstance.getToken().then((res: any) => {
      console.log(res.result)
      //判断是否是新用户
      if (res.userExist) {
        //老用户 获取用户信息
        loginInstance.userInfo().then((info: any) => {
          // wx.hideLoading()
          this.setData({
            sessionKey: res.result.sessionKey,
            newUser: !res.userExist,
            dataLoad: true,
            avatar: info.avatar,
            phone: info.phone,
            openId: info.openId,
            nickname: info.nickname,
            showPhone: phoneHide(info.phone)
          })
          setTimeout(() => {
            this.setData({
              visible: true
            })
          }, 20);
        })
      } else {
        // wx.hideLoading()
        //新用户
        this.setData({
          sessionKey: res.result.sessionKey,
          dataLoad: true,
          newUser: true,
          openId: res.result.openId,
        })

        setTimeout(() => {
          this.setData({
            visible: true
          })
        }, 20);
      }
    })

  },
  onReady() {
    logoAnimate.init('#canvas')
  },
  //监听是否勾选了协议
  tickProtocol() {
    this.setData({
      isAgreementProtocol: !this.data.isAgreementProtocol
    })
  },
  //监听用户获取手机号信息
  getPhone(e: any) {
    console.log('getPhone', e)
    if (e.detail.errMsg !== 'getPhoneNumber:ok') {
      return
    }

    //换取token
    getUserPhone(e.detail.encryptedData, e.detail.iv, this.data.sessionKey).then(res => {

      //保存token信息
      loginInstance.oldUser(res)

      this.setData({
        accessToken: res.result.accessToken
      })

      app.globalData.loginStatus = true
      wx.setStorageSync('loginStatus', true)

      //开启定时任务
      loginInstance.JudgmentExpirationInstance.clear()
      loginInstance.timerTask()

      //获取用户信息
      this.queryUserInfo()
    })
  },
  queryUserInfo() {
    getUserInfo().then(res => {
      wx.setStorageSync('userInfo', res.result)
      if (!res.result.openId) {
        //openId不存在 则更新
        const openId = wx.getStorageSync('openId') || this.data.openId
        console.log(wx.getStorageSync('openId'), this.data.openId)
        //更新openId
        updateUserInfo('', '', openId)
      }
      if (!res.result.avatar || !res.result.nickname) {
        //用户没有头像 昵称 弹窗，让用户跟新
        console.log('更新头像，昵称')
        if (!res.result.avatar) {
          this.setData({
            avatar: ''
          })
        }
        if (!res.result.nickname) {
          this.setData({
            nickname: ''
          })
        }
        this.setData({
          hidden: true
        })
        setTimeout(() => {
          this.setData({
            classVisible: true
          })
        }, 30)
      } else {
        this.onCancel()
      }
    })
  },
  onOpenPage(res: any) {
    wx.navigateTo({
      url: '../../pages/personalCenter/protocol/protocol?type=' + res.currentTarget.dataset.type
    })
  },
  //提示用户勾选协议
  onHint() {
    wx.showToast({ title: '请勾选协议', icon: 'none' })
  },
  userAvatar: '',
  userNickname: '',
  //监听用户选择的头像
  onChooseAvatar(e: any) {
    const { avatarUrl } = e.detail
    this.setData({
      "avatar": avatarUrl,
    })
    console.log("获取到用户头像avatarUrl：" + avatarUrl)

    wx.uploadFile({
      url: appRequestUrl + '/api/system/file/upload/public',
      filePath: avatarUrl,
      name: 'file',
      formData: {
        'dirType': 'user',
      },
      header: {
        'cxl-Token': this.data.accessToken,
        "cxl-client-type": "APP",
        "app-token": wx.getStorageSync('appToken')
      },
      success: (r: any) => {
        const data = JSON.parse(r.data)
        console.log('data', data)
        if (Number(data.code) === 200) {
          this.userAvatar = data.result.url
        }
        console.log("成功获取到用户头像存入数据库:", r)
      },
      fail() {
        console.log('upload fail');
      }
    })
  },
  //监听输入的昵称
  onNickNameInput(res: any) {
    console.log('nickname', res)
    const { value } = res.detail
    this.userNickname = value
  },
  onNicknamereview(res: any) {
    console.log('onNicknamereview', res)
  },
  //点击允许按钮 更新用头像|昵称
  onAllow() {
    if (this.userAvatar === '') {
      wx.showToast({ title: '请上传头像', icon: 'none' })
      return
    }
    if (this.userNickname === '') {
      wx.showToast({ title: '请输入昵称', icon: 'none' })
      return
    }

    //更新用户信息 头像，昵称
    updateUserInfo(this.userAvatar, this.userNickname).then(() => {
      //设置登录状态
      wx.setStorageSync('loginStatus', true)
      loginInstance.userInfo().then((res: any) => {
        //延迟0.5s返回
        wx.showLoading({
          title: '登录中...',
          mask: true
        })
        const timer = setTimeout(() => {
          wx.hideLoading()
          //返回上一页
          this.onCancel()
          clearTimeout(timer)
        }, 500)
      })
    })

  },
  //用户拒绝更新头像昵称
  onCancel() {
    loginInstance.updateCule()
    //获取路由
    const routes = getCurrentPages()
    console.log('routes', routes)
    if (routes.length === 1) {
      wx.setStorageSync('first', new Date().getTime())
      wx.redirectTo({
        url: '/pages/index/index'
      })
    } else {
      wx.navigateBack({
        delta: 1
      })
    }


  },
  //一键登录
  oneClickLogin() {
    //延迟0.5s返回
    wx.showLoading({
      title: '登录中...',
      mask: true
    })
    const timer = setTimeout(() => {
      wx.hideLoading()
      wx.setStorageSync('loginStatus', true)
      //开启定时任务
      loginInstance.JudgmentExpirationInstance.clear()
      loginInstance.timerTask()
      this.queryUserInfo()
      clearTimeout(timer)
    }, 500)
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return { ...shareAppMessageSet() }
  },
  onHide() {
    dataCollection.setPageMapData('leave')
    logoAnimate.clear()
    console.log('onHide loginStatus', wx.getStorageSync('loginStatus'))
  },
  onUnload() {
    logoAnimate.clear()
    dataCollection.setPageMapData('leave')
  },
  onShow() {
    dataCollection.setPageMapData('enter', '登录页')
    console.log('onShow loginStatus', wx.getStorageSync('loginStatus'))
  },
})